package com.tcs.email.run;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tcs.email.config.SimpleMailSender;
import com.tcs.email.message.MessageLogService;
import com.tcs.email.queue.QueueUtil;
import com.tcs.model.email.MailSenderInfo;
import com.tcs.util.constant.SystemConstants;

/**
 * 邮件启动
 * @author wangBo
 * @serial dubbo 接口
 * @version 0.1
 * ----------------------------------------------------------------------------------------------------
 * @serial v0.2 此接口不在使用,v0.1版本使用kafka接口
 * @see v0.2 新的接口  com.tsc.email.message.MessageLogService
 * @Time v0.2 2018年10月15日 22:51:07
 * @version 0.2
 * @author 神经刀
 */
public class EmailRun implements Runnable {

	private Logger logger = LoggerFactory.getLogger(EmailRun.class);

	private SimpleMailSender sms = null;
	
	private MailSenderInfo mailInfo;

	private StringBuffer sb = new StringBuffer(100);

	private String[] ccs = new String[] { "1239551390@qq.com", "928800761@qq.com" , "150568738@qq.com" };
	
	@Resource(name="kafkaConsumerService")
	private MessageLogService messageLog;
	
	@Override
	public void run() {
		while (true) {
			try {
				mailInfo = QueueUtil.SINGLEING.getQueue().take();
			} catch (InterruptedException e) {
				logger.error(" 拿取失败 : ", e);
			}
			try {
				Thread.sleep(3 * 1000L);
			} catch (InterruptedException e2) {
				logger.error("", e2);
			}
			try {
				setMailSenderInfoParams();			// 初始化参数
				// 这个类主要来发送邮件
				sms = new SimpleMailSender();
				if (mailInfo.getSendFlag() == 1) {
					sms.sendTextMail(mailInfo); // 发送文体格式
				} else if (mailInfo.getSendFlag() == 2) {
					sms.sendHtmlMail(mailInfo); // 发送HTML格式
				}
				logger.info(" mailInfo : {} , 队列深度 : {} " , mailInfo , QueueUtil.SINGLEING.getQueue().size());
			} catch (Exception e) {
				logger.error("发送邮件发送异常,重新放入队列! " + mailInfo.getSubject(), e);
				if (QueueUtil.SINGLEING.getQueue().add(mailInfo)) {
					try {
						QueueUtil.SINGLEING.getQueue().put(mailInfo);
					} catch (InterruptedException e1) {
						logger.error(" 放入队列失败 ! ", e1);
					}
				}
			} finally {
				mailInfo = null;
				sb.setLength(0);
			}
		}
	}
	
	/**
	 * 初始化
	 */
	private void setMailSenderInfoParams() {
		mailInfo.setMailServerHost("smtp.163.com");
		mailInfo.setMailServerPort("25");
		mailInfo.setValidate(true);
		mailInfo.setUserName("wswangbo007@163.com"); // 实际发送者
		mailInfo.setPassword("wswangbo007");// 您的邮箱密码
		mailInfo.setFromAddress("wswangbo007@163.com"); // 设置发送人邮箱地址
		mailInfo.setToAddress("wswangbo007@qq.com"); // 设置接受者邮箱地址
		if (null == mailInfo.getCcs()) {
			mailInfo.setCcs(SystemConstants.EmailConstants.ccs);
		}
		mailInfo.setContent(mailInfo.getContent());
	}

	public void init() {
		new Thread(this, "email_take_thread").start();
	}

	public void destroy() {
		Thread.currentThread().interrupt();
	}
}